<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>缓存菜单</title>

    <style>
        body {
            height: 4000px;
        }
        
        #box {
            position: absolute;
            width: 80px;
            height: 100px;
            background-color: red;
            right: 0;
            top: 0;
        }
    </style>
</head>

<body>
    <div id="box"></div>
</body>
<script>
    window.onload = function() {
        var box = document.getElementById('box');
        var scrollTop = document.documentElement.scrollTop;
        var windowsHeight = document.documentElement.clientHeight;
        var iH = scrollTop + Math.ceil((windowsHeight - box.offsetHeight) / 2);
        Start(iH);


        window.onscroll = function() {
            var box = document.getElementById('box');
            var scrollTop = document.documentElement.scrollTop;
            console.log(scrollTop);
            var windowsHeight = document.documentElement.clientHeight;
            var iH = scrollTop + Math.ceil((windowsHeight - box.offsetHeight) / 2);
            Start(iH);
        }
        window.onresize = function() {
            var box = document.getElementById('box');
            var scrollTop = document.documentElement.scrollTop;
            var windowsHeight = document.documentElement.clientHeight;
            var iH = scrollTop + Math.ceil((windowsHeight - box.offsetHeight) / 2);
            Start(iH);
        }
    }

    var time = null;

    function Start(targer) {
        var box = document.getElementById('box');
        clearInterval(time);
        time = setInterval(function() {
            var speed = (targer - box.offsetTop) / 8;
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
            if (box.offsetTop == targer) {
                clearInterval(time);
            } else {
                box.style.top = (box.offsetTop + speed) + 'px';
            }
        }, 30);

    }
</script>

</html>